package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("/cargo/factory")
@Controller
public class FactoryController extends BaseController {
    @Reference
    private FactoryService factoryService;

    //查询厂家信息
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize) {
        FactoryExample factoryExample = new FactoryExample();
        //展示状态正常的厂家
        factoryExample.createCriteria().andStateEqualTo("1");
        PageInfo<Factory> pageInfo = factoryService.findByPage(factoryExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/factory/factory-list";
    }

    //跳转到添加页面，因为WEB-INF下的页面浏览器无法直接访问
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "cargo/factory/factory-add";
    }

    //保存新建厂家信息或修改厂家信息
    @RequestMapping("/edit")
    public String edit(Factory factory) {
        if (StringUtils.isEmpty(factory.getId())) {
            factoryService.save(factory);
        } else {
            factoryService.update(factory);
        }
        return "redirect:/cargo/factory/list";
    }

    //修改厂家信息
    @RequestMapping("/toUpdate")
    public String toUpdate(HttpServletRequest request, String id) {
        Factory factory = factoryService.findById(id);
        request.setAttribute("factory", factory);
        return "cargo/factory/factory-update";
    }


    //根据ID删除厂家记录
    @RequestMapping("/delete")
    public String delete(String id) {
        factoryService.delete(id);
        return "redirect:/cargo/factory/list";
    }
}
